package task

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/global"
	"strings"
	"time"

	"gorm.io/gorm"
)

type Site struct {
	Spec string
}

// 站长过期时间
func SiteEnd() {
	global.OC_DB.Transaction(func(tx *gorm.DB) error {
		var regions []*admin.Region
		tx.Where("manage_id IS NOT NULL AND over_time < ?", time.Now().Unix()*1000).Find(&regions)
		if len(regions) == 0 {
			return errors.New("暂无站点开通")
		}
		res := tx.Model(&admin.Region{}).Where("manage_id IS NOT NULL AND over_time < ?", time.Now().Unix()*1000).Updates(map[string]interface{}{"manage_id": nil, "over_time": nil})
		if res.RowsAffected == 0 || res.Error != nil {
			return errors.New("未知错误500")
		}
		fmt.Println(111)
		var accounts []*admin.Account
		var regionStr []string
		var ids []int
		if len(regions) != 0 {
			for _, v := range regions {
				ids = append(ids, int(v.ManageId))
				regionStr = append(regionStr, fmt.Sprintf("region_link LIKE '%v%v,%%'", v.Link, v.ID))
			}
		}
		if len(ids) == 0 {
			return errors.New("暂无站点开通")
		}
		tx.Where("id IN (?)", ids).Find(&accounts)

		tx.Model(&admin.Account{}).Where("id IN (?)", ids).Updates(map[string]interface{}{"belong": 1, "region_link": ",1,"})
		var strs []string
		for _, v := range accounts {
			strs = append(strs, fmt.Sprintf("account_link LIKE '%v%v,%%'", v.AccountLink, v.ID))
		}
		newStr := strings.Join(strs, " OR ")
		newRegionStr := strings.Join(regionStr, " OR ")
		tx.Model(&admin.Account{}).Where(newStr).Where(newRegionStr).Update("status", 0)

		return nil
	})

}

var SiteTask = &Site{Spec: "0 0 0 * * ?"}
